package com.wyy.mall.tiny.config;

import com.wyy.mall.tiny.component.JwtAuthenticationTokenFilter;
import com.wyy.mall.tiny.component.RestAuthenticationEntryPoint;
import com.wyy.mall.tiny.component.RestfulAccessDeniedHandler;
import com.wyy.mall.tiny.dto.AdminUserDetails;
import com.wyy.mall.tiny.mbg.model.UmsAdmin;
import com.wyy.mall.tiny.mbg.model.UmsPermission;
import com.wyy.mall.tiny.service.UmsAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import java.util.List;

/**
 * created by 伍猷煜 on 2021/5/13 22:25 星期四
 */
@Configuration
@EnableWebSecurity
// 开启基于方法的安全认证机制，也就是说在web层的controller启用注解机制的安全确认
// controller层方法使用@PreAuthorize("hasAuthority('admin')")才会生效
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UmsAdminService mUmsAdminService;
    @Autowired
    private RestAuthenticationEntryPoint mRestAuthenticationEntryPoint;
    @Autowired
    private RestfulAccessDeniedHandler mRestfulAccessDeniedHandler;
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
          UmsAdmin admin = mUmsAdminService.getAdminByUsername(username);
          if (admin != null) {
              List<UmsPermission> permissions = mUmsAdminService.getPermissionList(admin.getId());
              return new AdminUserDetails(admin, permissions);
          }
          throw new UsernameNotFoundException("用户名或密码错误");
        };
    }
    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 添加用户详情服务和密码加密方式
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        http.csrf().disable() // 使用jwt，不需要CSRF
                // 基于token，不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 允许对于网站静态资源的无授权访问
                .antMatchers(HttpMethod.GET, "/", "/*.html", "/favicon.ico", "/**/*.html",
                        "/**/*.css", "/**/*.js", "/swagger-resources/**", "/v2/api-docs/**")
                .permitAll()
                // 对登录注册允许匿名访问
                .antMatchers("/admin/login", "/admin/register").permitAll()
                // 跨域请求会先进行一次options请求
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                // 测试时全部打开
                //.antMatchers("/**").permitAll()
                // 除上面所以请求都需要鉴权认证
                .anyRequest().authenticated();
        // 禁用缓存
        http.headers().cacheControl();
        // 添加jwt filter
        http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        // 异常处理：添加自定义未授权和未登陆结果返回
        http.exceptionHandling()
                .accessDeniedHandler(mRestfulAccessDeniedHandler)
                .authenticationEntryPoint(mRestAuthenticationEntryPoint);
    }
}
